package com.producer.controller;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SendMsgController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @RequestMapping("sendMsg")
    public String sendMsg(String message) {
        rocketMQTemplate.syncSend(
                "01-boot-hello",//第一个参数: destination = Topic + ":" + tag
                message //第二个参数: 消息内存
        );
        return message;
    }

    @RequestMapping("asyncSend")
    public String asyncSend(String message) {
        rocketMQTemplate.asyncSend(
                "01-boot-hello",
                message,
                new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        System.out.println("发送成功");
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        System.out.println("发送失败");
                    }
                }
        );
        return message;
    }

    @RequestMapping("sendOneWay")
    public String sendOneWay(String message) {
        rocketMQTemplate.sendOneWay(
                "01-boot-hello",
                message
        );
        return message;
    }

    @RequestMapping("sendDelay")
    public String sendDelay(String message) {
        //用这个工具类帮我们去做转换字符串工作,使用build方法即可
        MessageBuilder<String> messageBuilder = MessageBuilder.withPayload(message);
        rocketMQTemplate.syncSend(
                "boot-delay",
                messageBuilder.build(),
                5000,
                2);
        return message;
    }

    @RequestMapping("filter")
    public String filter(String message, String tag, Integer age) {
        rocketMQTemplate.sendOneWay(
                "boot-filter:" + tag,
                message);
/*        Map<String, Object> map = new HashMap<>();
        map.put("age", age);
        rocketMQTemplate.convertAndSend("boot-filter",message,map);*/
        return message;
    }
}